#
# Package.
#

package iSOCK::Model::DSTP;

#
# Base.
#

use Moose;
use namespace::autoclean;

BEGIN { extends 'Catalyst::Model' }

#
# Dependencies.
#

use HTTP::Request::Common;
use LWP::UserAgent;
use XML::LibXML;

#
# Subs.
#

sub query_result_loh {
  my ( $self, $option ) = @_;
  
  if ( $option->{type} ) {
    $option->{type} = {
      cell     => 1,
      block    => 2,
      library  => 3,
      design   => 4,
      project  => 5,
      kit      => 6,
      document => 7,
    }->{$option->{type}};
    
    return unless $option->{type};
  }
  
  if ( my $ua = LWP::UserAgent->new ) {
    my $dstp_host      = 'webdev.corp.atmel.com';
    my $dstp_rest_url  = "http://$dstp_host:8060/dstp/restful";
    my $is_deliverable = $option->{what} =~ /deliverable/;
    my $url            = $dstp_rest_url . '/' . ( $is_deliverable ? 'search' : 'dissues' ) . '.jsp';
    my @credentials    = ( user => 'xcaron', password => 'dstp463' );
    my @options        = map { $_ => $option->{$_} } $is_deliverable ? qw( name version type status ) : qw( deliverable );
    
    $ua->no_proxy ( $dstp_host );
    
    my $response = $ua->request ( POST $url => [ @credentials, @options ] );

    if ( $response->is_success ) {
      my $parser = XML::LibXML->new;

      if ( my $dom = $parser->parse_string ( $response->decoded_content ) ) {
        return [ map { { map { lc $_->localname, $_->textContent } grep { $_->localname } $_->childNodes } } $dom->findnodes ( '/results/' . ( $is_deliverable ? 'deliverable' : 'issue' ) ) ];
      }
    }
  }

  return;
}

sub component_name {
  return {
    ADC_CONTROLLER => 'ADCC',
    DEBUG_UNIT     => 'DBGU',
    DES3           => 'TRIPLE-DES ',
    EMAC           => 'E-MACB',
    ETHERNET_MACB  => 'E-MACB',
    MSSC           => 'MS-SC',
    USB_DEVICE     => 'USB-DEV-1.1',
  }->{$_[1]} || $_[1];
}

sub versions {
  my ( $self, $name ) = @_;
  
  if ( my $loh = $self->query_result_loh ({ what => 'deliverable', name => $name }) ) {
    return [ sort map { $_->{version} } @$loh ];
  }
  
  return;
}

sub issues {
  my ( $self, $name, $version ) = @_;
  
  my $hash = sub {
    my ( $h ) = @_;

    my $rh = { map { $_ => $h->{$_} } qw( issue_id requestor created_on closed_on status owner summary description ) };
    
    $rh->{issue_url}   =  "http://webdev.corp.atmel.com:8060/dstp/home/login.jsp?dir=issue&id=$rh->{issue_id}";
    $rh->{description} =~ s/\r//g;
    $rh->{name}        =  $name;
    $rh->{version}     =  $version;

    return $rh;
  };

  if ( my $loh = $self->query_result_loh ({ what => 'deliverable', name => $name, version => $version }) ) {
    if ( my $issues = $self->query_result_loh ({ what => 'issues', deliverable => $loh->[0]->{id} }) ) {
      return [ map { $hash->( $_ ) } @$issues ];
    }
  }
  
  return;
}

#
# True.
#

1;
